<style>
  div[lay-id="productionPlanTable"] .layui-table-cell {
    padding: 0 5px;
  }

  .table-auto .layui-table-cell {
    height: auto;
  }

  .template-box .w-auto {
    width: 110px !important;
    text-align: left;
    padding: 9px 0;
  }

  .template-box .addTable {
    height: 30px;
    line-height: 30px;
    padding: 0 10px;
  }

  .msg-none .layui-none {
    display: none !important;
  }

  .flex-item {
    display: flex;
    border-bottom: 1px solid #e6e6e6;
  }

  .left-btn {
    flex: 1;
    text-align: left;
  }

  .flex-between {
    width: calc(100% - 40px);
    display: flex;
    justify-content: space-between;
  }

  body .layui-table tbody tr.disabledBg {
    background-color: #f5f5f5 !important;
  }

  .layui-table-page-left {
    text-align: left;
  }

  .scroll-table-5-4 .layui-table-body {
    max-height: 535px;
  }

  .scroll-table-4-5 .layui-table-body {
    max-height: 490px;
  }

  /*   添加生产计划   */
  .addProductionPlanForm-title,
  .examineProductionPlanForm-title {
    width: 100%;
  }

  .addProductionPlanForm-title .title,
  .examineProductionPlanForm-title .title {
    display: inline-block;
    font-size: 16px;
    font-weight: bold;
    color: #333333;
    line-height: 19px;
    position: relative;
    padding: 6px 0 19px 0;
  }

  .addProductionPlanForm-title .title:after,
  .examineProductionPlanForm-title .title:after {
    content: "";
    display: block;
    position: absolute;
    left: 0;
    bottom: 0;
    width: calc(100% + 6px);
    height: 3px;
    background: #0a8b0a;
  }

  .line {
    width: 100%;
    height: 1px;
    background-color: #f8f8f8;
  }

  .addProductionPlanFormBox {
    padding: 20px 0;
  }

  .addProductionPlanFormBox .layui-col-md4 {
    margin: 5px 0;
  }

  .addProductionPlanFormBox .layui-form-label,
  addProductionPlanFormItem .layui-form-label {
    padding: 9px;
    width: 115px;
    font-size: 14px;
    font-weight: 400;
    color: #999999;
  }

  .addProductionPlanFormBox .layui-input-inline>input[readonly] {
    border-color: rgba(0, 0, 0, 0);
    outline: none;
  }

  .addProductionPlanFormBox .layui-input-inline>input[readonly]:focus,
  .addProductionPlanFormBox .layui-input-inline>input[readonly]:hover {
    border-color: transparent !important;
    outline: none;
  }

  form[lay-filter="examineProductionPlanForm"] textarea {
    width: 90%;
    resize: none;
    padding: 5px 10px;
    height: 100px;
    box-sizing: border-box;
  }

  form[lay-filter="examineProductionPlanForm"] .layui-table-cell {
    height: auto;
  }

  form[lay-filter="examineProductionPlanForm"] .layui-table-cell>img {
    height: 100%;
  }

  .addProductionPlanFormItem {
    padding: 15px 0 0 0;
  }

  .addProductionPlanFormItem .layui-input-block {
    margin-left: 133px;
    padding-right: 90px;
    box-sizing: border-box;
  }

  .open-details-box::-webkit-scrollbar {
    width: 0 !important;
  }
</style>
<form lay-filter="addProductionPlanFormDiv" class="layui-form open-form">
  <div class="open-model" id="addProductionPlanFormContent">
    <div class="open-auto">
      <input type="hidden" name="id" />
      <input type="hidden" name="productTypeName" />
      <input type="hidden" name="materialNatureName" />
      <div class="layui-form-item">
        <div class="addProductionPlanForm-title">
          <h3 class="title">计划信息</h3>
        </div>
        <div class="line"></div>
        <div class="layui-form-item layui-row addProductionPlanFormBox">
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">计划来源：</label>
            <div class="layui-input-inline">
              <select id="planSource" name="planSource" lay-filter="planSource" lay-verify="required" required>
                <option value="">请选择</option>
                <option value="temporary">一般计划</option>
                <option value="order">量产订单</option>
                <option value="finish">成品销售订单</option>
              </select>
            </div>
          </div>
          <!-- <div class="layui-inline layui-col-md4" id="orderTypeBox" style="display: none">
            <label class="layui-form-label">订单类型：</label>
            <div class="layui-input-inline">
              <select id="orderType" name="orderType"></select>
            </div>
          </div> -->
          <div class="layui-inline layui-col-md4" id="orderIdBox" style="display: none">
            <div style="display: flex; align-items: center">
              <label class="layui-form-label">订单编号：</label>
              <div class="layui-input-inline">
                <!-- <select id="orderId" disabled name="orderId" lay-filter="orderId" lay-search=""></select> -->
                <input name="orderId" id="orderId" class="layui-input" type="hidden" disabled />
                <input name="orderCode" class="layui-input" type="text" disabled />
              </div>
              <button class="layui-btn layui-btn-xs" id="orderFun" type="button">
                选择订单
              </button>
            </div>
          </div>
          <!-- <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">计划分类：</label>
            <div class="layui-input-inline">
              <input name="planClassifyId" type="hidden" />
              <div class="layui-input-block" id="selectPlanClassify" style="margin-left: 0px"></div>
            </div>
          </div> -->
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">计划类型：</label>
            <div class="layui-input-inline">
              <select name="planTypeId" lay-search="" id="planTypeId"></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">计划性质：</label>
            <div class="layui-input-inline">
              <!-- <select
                id="planNature"
                name="planNature"
                lay-verify="required"
                value="entirety"
                required
                lay-filter="planNature"
              ></select> -->
              <input name="planNature" id="planNature" value="整体工序计划" disabled class="layui-input" />
            </div>
          </div>
          <div id="planInfoBox">
            <div class="layui-inline layui-col-md4" id="creatorNameBox">
              <label class="layui-form-label">计划创建人：</label>
              <div class="layui-input-inline">
                <input name="creatorName" disabled class="layui-input" type="text" />
              </div>
            </div>
            <div class="layui-inline layui-col-md4" id="phoneBox">
              <label class="layui-form-label">创建人电话：</label>
              <div class="layui-input-inline">
                <input name="phone" disabled class="layui-input" type="text" />
              </div>
            </div>
            <!-- <div class="layui-inline layui-col-md4" id="auditPersonBox">
              <label class="layui-form-label">计划审核人：</label>
              <div class="layui-input-inline">
                <input name="auditPerson" class="layui-input" type="text" />
              </div>
            </div> -->
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="addProductionPlanForm-title">
          <h3 class="title">计划生产物料信息</h3>
        </div>
        <div class="line"></div>
        <div class="layui-form-item layui-row addProductionPlanFormBox" style="display: none">
          <div class="layui-inline layui-col-md4" id="signOrNotBox" style="display: none">
            <label class="layui-form-label">是否已签约：</label>
            <div class="layui-input-inline">
              <!-- <select name="signOrNot" lay-filter="signOrNot">
                                       <option value="yes">已签约</option>
                                       <option value="no">未签约</option>
                                   </select>-->
              <!--                            <input name="signOrNot" type="hidden"/>-->
              <input name="signOrNotDesc" class="layui-input" type="text" />
            </div>
          </div>
          <div class="layui-inline layui-col-md4" id="contractIdBox" style="display: none">
            <label class="layui-form-label">选择所属合同：</label>
            <div class="layui-input-inline">
              <!--                            <select name="contractId" id="contractId" lay-search="" ></select>-->
              <input name="contractId" type="hidden" />
              <input name="contractName" class="layui-input" type="text" />
            </div>
          </div>
          <div class="layui-inline layui-col-md4" style="display: flex; align-items: center">
            <label class="layui-form-label">物料编号：</label>
            <div class="layui-input-inline">
              <input name="customerSkuCode" id="customerSkuCode" class="layui-input" type="text" disabled />
              <input name="productDetailId" id="productDetailId" class="layui-input" type="hidden" />
              <input name="orderProId" class="layui-input" type="hidden" />
            </div>
            <!-- <button
              class="layui-btn layui-btn-xs"
              id="checkSkuFun"
              style="display: none"
            >
              选择物料
            </button> -->
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">物料名称：</label>
            <div class="layui-input-inline">
              <input name="customerSkuName" class="layui-input" type="text" disabled />
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">物料规格码：</label>
            <div class="layui-input-inline">
              <input name="customerSkuSpec" class="layui-input" type="text" disabled />
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">物料类型：</label>
            <div class="layui-input-inline">
              <!--                            <select name="productTypeId" lay-filter="addProductionPlanFormProductTypeId" disabled></select>-->
              <input name="productTypeId" type="hidden" />
              <input name="productTypeName" class="layui-input" type="text" disabled />
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">物料属性：</label>
            <div class="layui-input-inline">
              <!--                            <select name="productTypeId" lay-filter="addProductionPlanFormProductTypeId" disabled></select>-->
              <input name="productNatureName" class="layui-input" type="text" disabled />
            </div>
          </div>
          <div class="layui-inline layui-col-md4" style="display: flex; align-items: center">
            <label class="layui-form-label">基准书：</label>
            <div class="layui-input-inline">
              <select name="bookId" id="bookId" disabled></select>
              <!-- <input name="bookId" class="layui-input"   id="bookId"></input> -->
            </div>
            <button class="layui-btn layui-btn-xs" type="button" id="bookIdBox">
              选择基准书
            </button>
            <!-- <button class="layui-btn layui-btn-xs" id="addBookFun">新增基准书</button> -->
          </div>
          <div class="layui-inline layui-col-md4" id="processIdBox" style="display: none">
            <label class="layui-form-label">选择工序：</label>
            <div class="layui-input-inline">
              <input name="processName" type="hidden" />
              <select name="processId" id="processId" lay-filter="processId" lay-search=""></select>
            </div>
          </div>

          <div id="demandQuantityBox" style="display: none">
            <div class="layui-inline layui-col-md4">
              <label class="layui-form-label">需求数量：</label>
              <div class="layui-input-inline">
                <input name="demandQuantity" id="demandQuantity" class="layui-input" type="text" disabled />
              </div>
            </div>
          </div>
          <div class="layui-inline layui-col-md4" id="residueQuantityBox" style="display: none">
            <label class="layui-form-label">订单剩余计划量：</label>
            <div class="layui-input-inline">
              <input name="residueQuantity" class="layui-input" type="text" disabled />
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">计划生产数量：</label>
            <div class="layui-input-inline">
              <input name="productionQuantity" class="layui-input" type="text" onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')" />
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">计划产出时间：</label>
            <div class="layui-input-inline">
              <input name="outputTime" class="layui-input" type="text" id="plannedOutputTime" autocomplete="off" />
            </div>
          </div>
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">交货时间：</label>
            <div class="layui-input-inline">
              <input name="shipmentTime" class="layui-input" type="text" id="addProductionPlanDeliveryTime" />
            </div>
          </div>
          <!-- <div
            class="layui-form-item addProductionPlanFormItem"
            id="orderRemarkBox"
            style="display: none"
          >
            <label class="layui-form-label">订单备注描述：</label>
            <div class="layui-input-block">
              <input name="orderRemark" class="layui-input" type="text" />
            </div>
          </div> -->

          <!-- <div class="layui-form-item addProductionPlanFormItem">
            <label class="layui-form-label">附件：</label>
            <div
              class="layui-input-block"
              style="display: flex; align-items: center"
            >
              <button
                class="layui-btn layui-btn-xs"
                type="button"
                id="openImgTable"
              >
                附件列表
              </button>
              <input name="accessory" type="hidden" id="accessoryFileId" />
            </div>
          </div> -->
          <div class="layui-form-item layui-row ">
            <div class="layui-inline layui-col-md4">
              <label class="layui-form-label">车间：</label>
              <div class="layui-input-inline">
                <select id="workshopId" name="workshopId" lay-filter="workshopId">
                </select>
              </div>
            </div>

            <div class="layui-form-item addProductionPlanFormItem">
              <label class="layui-form-label">备注说明：</label>
              <div class="layui-input-inline">
                <input name="remark" class="layui-input" type="text" />
              </div>
            </div>
          </div>
        </div>
        <div id="skuPlanTableBox">
          <button class="layui-btn" type="button" style="margin-top: 15px" id="addSkuPianFun">
            配置物料信息
          </button>
          <table id="skuPlanTable" lay-filter="skuPlanTable"></table>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button class="layui-btn" lay-filter="addProductionPlanExamine" lay-submit data-type="affirm" type="button">
          确认提交
        </button>
        <button class="layui-btn color-reseda" lay-filter="addProductionPlanFormSubmit" lay-submit data-type="toconfirmed" type="button">
          暂时保存
        </button>
      </div>
    </div>
</form>
<script type="text/html" id="skuPlanTableBar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
  layui.use(["form", "table", "admin", "jquery", "laydate"], async function () {
    let form = layui.form;
    let table = layui.table;
    let admin = layui.admin;
    let $ = layui.jquery;
    let laydate = layui.laydate;
    const nowData = { ...parentData };
    console.log('nowData', nowData);

    let data = nowData.data;
    let orderObj = {
      customerSkuCode: "",
      productDetailId: "",
      orderProId: "",
      customerSkuName: "",
      customerSkuSpec: "",
      productTypeId: "",
      productTypeId: "",
      productTypeName: "",
      productNatureName: "",
      bookId: "",
      bookId: "",
      processName: "",
      processId: "",
      residueQuantity: "",
      shipmentTime: "",
      demandQuantity: "",
      productionQuantity: "",
      outputTime: "",
      orderRemark: "",
      accessory: "",
      remark: "",
    };
    let initOrderObj = {
      shipmentTime: "",
      orderRemark: "",
      orderCreatorName: "",
      signOrNot: "",
      signOrNotDesc: "",
      contractName: "",
      contractId: "",
    };
    let initSkuObj = {
      orderProId: "",
      customerSkuCode: "",
      productDetailId: "",
      customerSkuName: "",
      customerSkuSpec: "",
      residueQuantity: "",
      demandQuantity: "",
      productTypeId: "",
      productTypeName: "",
      orderProId: "",
      bookId: "",
      processId: "",
    };
    const deviceRes = await admin
      .initDataSelectPro(
        "enterprise/device/admin/deviceWorkshop/list",
        {},
        "workshopId",
        "车间",
        () => { },
        "name"
      )
    const deviceList = deviceRes.map((v) => {
      return {
        label: v.name,
        value: v.id,
      };
    });
    table.render({
      elem: "#skuPlanTable",
      data: [],
      minHeight: 400,
      limit: 99999,
      cols: [
        [
          {
            align: "center",
            title: "序号",
            type: "numbers",
            width: 50,
            fixed: "left",
          },
          {
            field: "productDetailId",
            align: "center",
            hide: true,
          },
          {
            field: "customerSkuCode",
            align: "center",
            title: "物料编号",
          },
          // { field: "planSourceDesc", align: "center", title: "计划订单类型" },
          { field: "customerSkuName", align: "center", title: "物料名称" },
          { field: "customerSkuSpec", align: "center", title: "物料规格码" },
          { field: "productTypeName", align: "center", title: "物料类型" },
          { field: "productNatureName", align: "center", title: "物料属性" },
          {
            field: "bookId",
            align: "center",
            title: "基准书",
            templet: (d) => {
              return `<button class="layui-btn layui-btn-xs" type="button" lay-event="checkBook">${d.bookId ? d.bookCode : "选择基准书"
                }</button>`;
            },
          },
          {
            field: "demandQuantityBox",
            align: "center",
            title: "需求数量",
            hide: true,
          },
          {
            field: "residueQuantityBox",
            align: "center",
            title: "订单剩余计划量",
            hide: true,
          },
          {
            field: "workshopId",
            align: "center",
            title: "车间",
            templet: admin.setTableSelect("workshopId", deviceList),
          },
          {
            field: "haveQuantity",
            align: "center",
            title: "库存数量",
          },
          {
            field: "productionQuantity",
            align: "center",
            title: "计划生产数量",
            templet: admin.setTableInput("productionQuantity"),
          },

          {
            field: "outputTime",
            align: "center",
            title: "生产截至时间",
            event: "editStartDate",
            // templet: admin.setTableInput("outputTime"),
          },
          {
            field: "shipmentTime",
            align: "center",
            title: "交货时间",
            event: "editStartDate",
            // templet: admin.setTableInput("shipmentTime"),
          },

          // {
          //   field: "accessory",
          //   align: "center",
          //   title: "附件",
          //   templet: (d) => {
          //     return d.accessory
          //       ? '<button class="layui-btn layui-btn-xs" type="button" lay-event="fujian" class="bookIdBox">查看附件</button>'
          //       : "-";
          //   },
          // },
          {
            field: "remark",
            align: "center",
            title: "备注说明",
            templet: admin.setTableInput("remark"),
          },
          {
            title: "操作",
            align: "center",
            fixed: "right",
            toolbar: "#skuPlanTableBar",
          },
        ],
      ],
      done: () => {
        $(" .layui-table-body, .layui-table-box, .layui-table-cell")
          .has("select")
          .css("overflow", "visible");

        admin.tableInputChange("skuPlanTable");
      },
    });

    if (
      nowData.planSourceType == "order" ||
      nowData.planSourceType == "finish"
    ) {
      let type = nowData.planSourceType
      $("#planSource").val(nowData.planSourceType);
      $("#planSource").attr("disabled", true);
      $("#orderFun").hide();
      console.log("nowData", nowData);
      form.val("addProductionPlanFormDiv", {
        orderId: nowData.orderId,
        orderCode: nowData.orderCode,
      });
      let detailUrl = "";
      if (type == "order") {
        detailUrl = "enterprise/sell/admin/order/detail/";
      } else if (type == "finish") {
        detailUrl = "enterprise/sell/admin/finishedOrder/detail/";
      }
      const res = await admin.reqPro(detailUrl + nowData.orderId);
      let obj = res.data;
      let list = [];
      if (type == "order") {
       await initSkuPlanTable(
          obj.orderProList,obj
        );
        form.val("addProductionPlanFormDiv", {
          orderId: obj.id,
          orderCode: obj.code,
        });
      } else if (type == "finish") {
        await initSkuPlanTable(obj.details,obj);
        form.val("addProductionPlanFormDiv", {
          orderId: obj.id,
          orderCode: obj.selCode,
          // shipmentTime: obj.deliveryTime,
        });
      }
      isOrderFun(true);

    }
    else if(nowData.planSourceType=="single"){
      $("#addSkuPianFun").hide(); 
      $("#planSource").val("temporary");
      $("#planSource").attr("disabled", true);
      initSkuPlanTable([nowData]);
    }
    if (nowData.eventName === "detail") {
      $("#customerSkuCode").attr("disabled", true);
      $("#planSource").attr("disabled", true);
      $("#planInfoBox").show();
      $("#orderFun").hide();
      $("#orderIdBox").show();
      $(".addProductionPlanFormBox").show();
      $("#skuPlanTableBox").hide();
      admin.setFormDisable("#addProductionPlanFormContent", true);
    } else if (nowData.eventName === "edit") {
      $("#customerSkuCode").attr("disabled", true);
      $("#planSource").attr("disabled", true);
      $('#skuPlanTableBox').hide()
      $(".addProductionPlanFormBox").show();

    } else {
      $("#planInfoBox").hide();
    }

    // 让所有div显示
    // $(".layui-col-md4").show();
    init();
    async function init() {
      await initCreateData(); // 确保所有initDataForm中的异步操作完成
      await initFormByType(nowData.type); // 然后执行initFormByType
      initDataForm(nowData.id);
    }

    // const xx = await admin.initDataSelectPro(
    //   "enterprise/device/admin/deviceWorkshop/list",
    //   {},
    //   "workshopId",
    //   "车间",
    //   () => {},
    //   "name"
    // );
    // console.log(1, xx);
 
   
    table.on("tool(skuPlanTable)", function (obj) {
      var data = obj.data;
      var layEvent = obj.event;
      var field = $(this).data("field");
      let tableList = table.cache["skuPlanTable"];
      var index = $(obj.tr).data("index");

      if (obj.event === "checkBook") {
        admin.putTempData("benData", data ? data : null);
        admin.formOpen({
          area: "1400px",
          offset: "35px",
          title: "基准书管理",
          path: "components/product/benManager.html",
          success: function () {
            parentData.typeName = "redio";
          },
          end: async function () {
            let objData = childData.obj ? childData.obj : {};
            if (objData.statusName == "待初审") {
              layer.msg("基准书状态为待初审，无法生成生产计划！", { icon: 2 });
              return false;
            }

            data["bookId"] = objData.id;
            data["bookCode"] = objData.code;
            obj.update(data);
            console.log(123, obj);

            console.log(table.cache["skuPlanTable"]);

            table.reload("skuPlanTable");
          },
        });
      } else if (obj.event === "editStartDate") {
        laydate.render({
          elem: this.firstChild,
          show: true, //直接显示
          type: "datetime",
          // closeStop: this,
          done: function (value, date) {
            // admin.setTableColHtml("skuPlanTable", index, field, value)
            table.cache["skuPlanTable"][index][field] = value;
            // data[field] = value;
            // obj.update(data);
            // table.reload("skuPlanTable", { data: tableList });
            console.log(table.cache["skuPlanTable"]);
          },
        });
      } else if (obj.event === "del") {
        // let list = xxxList[nodeIndex].processDeviceList;
        // list = list.filter((v) => {
        //   return v["id"] != id;
        // });
        // xxxList[nodeIndex].processDeviceList = list;
        tableList = tableList.filter((v) => {
          return v["productDetailId"] != data.productDetailId;
        });
        // obj.del();
        // tableList.splice(index, 1);
        console.log(tableList);
        table.reload("skuPlanTable", { data: tableList });
      }
    });
    async function initCreateData() {
      laydate.render({
        elem: "#plannedOutputTime",
        type: "datetime",
      });

      laydate.render({
        elem: "#addProductionPlanDeliveryTime",
        type: "datetime",
      });
      form.on("select(planSource)", function (d) {
        form.val("addProductionPlanFormDiv", {
          ...orderObj,
          orderId: "",
          orderCode: "",
        });
        console.log(3333);
        
        table.reload("skuPlanTable", { data: [] });
        if (d.value == "order" || d.value == "finish") {
          isOrderFun(true);
          $("#addSkuPianFun").hide();
        } else {
          $("#addSkuPianFun").show();

          isOrderFun(false);
        }
      });
      //订单类型
      // await admin.getDictListPro("orderType", "production_plan_order_type", "订单类型");
      //计划性质
      await admin.getDictListPro(
        "planNature",
        "production_plan_nature",
        "计划性质",
        (d, obj) => {
          if (d.value == "entirety") {
            //整体生产计划'
            $("#processIdBox").hide({ duration: 300 });
          } else if (d.value == "process") {
            $("#processIdBox").show({ duration: 300 });
          }
        }
      );
      //计划类型
      await admin.initDataSelectPro(
        "production/productionPlan/admin/productionType/list",
        { businessProperty: 1, page: 1, limit: 9999 },
        "planTypeId",
        "计划类型",
        () => { },
        "name"
      );

      //计划分类
      // admin.initDataSelectTree(
      //   true,
      //   "production/productionPlan/admin/productionCategory/getTreeData",
      //   null,
      //   "selectPlanClassify",
      //   data ? data?.planClassifyId : null,
      //   "计划分类",
      //   "planClassifyId",
      //   null
      // );
    }
    async function initDataForm(id) {
      if (id) {
        const { data } = await admin.reqPro(
          "production/productionPlan/admin/productionPlan/getProductionPlanDetails",
          { id }
        );
        await initBenchmarkBookData(data.productDetailId);
        if (data.planNature == "process") {
          $("#processIdBox").show();
          // await admin.initDataSelectPro(
          //   "enterprise/benchmarkBook/admin/benchmarkBook/getEchnologyBy/" +
          //   data.bookId,
          //   {},
          //   "processId",
          //   "工序",
          //   (d, obj) => {
          //     console.log("d", d);
          //   }
          // );
        }
        if (data.accessory) {
          $("#accessoryPath").html(
            "<a href='" +
            data.accessory +
            "' target='_blank'>" +
            data.accessory +
            "</a>"
          );
        } else {
          $("#accessoryPath").html(
            "<span style='cursor: default;'>暂无附件</span>"
          );
        }

        form.val("addProductionPlanFormDiv", data);
      }
    }
    async function initFormByType(type) {
      if (nowData.productDetailId) {
        if (type === "基准书生成") {
          // 基准书
          $("#customerSkuCode").attr("disabled", true);
          form.val("addProductionPlanFormDiv", {
            planSource: "research",
          });
          $("#planSource").attr("disabled", true);
          initSkuData(nowData.productDetailId);
          initBenchmarkBookData(nowData.productDetailId);
        }
      } else {
        $("#checkSkuFun").show();
      }
    }
    // 赋值物料
    async function initSkuData(productDetailId) {
      const { data } = await admin.reqPro(
        "enterprise/product/admin/productDetailWMS/get",
        { productDetailId }
      );
      form.val("addProductionPlanFormDiv", {
        customerSkuCode: data.skuCode,
        customerSkuName: data.skuName,
        customerSkuSpec: data.skuSpec,
        // residueQuantity: data.residueQuantity,
        demandQuantity: data.quantity,
        productTypeId: data.productDetailId,
        productDetailId: data.productDetailId,
        productTypeName: data.productTypeName,
        orderProId: data.orderProId,
      });
    }
    // 赋值基准书
    async function initBenchmarkBookData(productDetailId) {
      const resData = await admin.initDataSelectPro(
        "enterprise/benchmarkBook/admin/benchmarkBook/getBookInfoBy/" +
        productDetailId,
        {},
        "bookId",
        "基准书",
        async (d, obj) => {
          form.val("addProductionPlanFormDiv", {
            accessoryFileId: "",
          });
          $("#processId").empty();
          $("#accessoryPath").html(
            "<span style='cursor: default;'>暂无附件</span>"
          );
          // $("#accessoryBtn").show();
          if (d.value) {
            // await admin.initDataSelectPro(
            //   "enterprise/benchmarkBook/admin/benchmarkBook/getEchnologyBy/" +
            //   d.value,
            //   {},
            //   "processId",
            //   "工序",
            //   (d, obj) => {
            //     console.log(111, obj);
            //     if (d.value) {
            //       form.val("addProductionPlanFormDiv", {
            //         processName: obj.name,
            //       });
            //     }
            //   }
            // );
            if (obj.drawUrl) {
              form.val("addProductionPlanFormDiv", {
                accessoryFileId: obj.drawUrl,
              });
              $("#accessoryPath").html(
                "<a href='" +
                obj.drawUrl +
                "' target='_blank'>" +
                obj.drawUrl +
                "</a>"
              );
              // $("#accessoryBtn").hide();
              $("#accessoryFileId").val(obj.drawUrl);
            }
          }
          form.render();
        },
        "code"
      );
      // if (resData.length == 0) {
      //   //弹窗是否跳转
      //   layer.confirm("当前物料没有基准书，是否跳转新增基准书弹窗？", { icon: 3, title: "提示" }, function (index) {
      //     // 关闭所有弹窗
      //     layer.closeAll();
      //     // window.location.href = '/admin/index.html#/res/planning/proTask';
      //     admin.formOpen({
      //       area: ["80%", "88%"],
      //       title: "生成基准书",
      //       path: "components/res/benchmarkBook/skuPlanTable.html",
      //       success: function () {
      //         parentData.eventName = "add";
      //         delete data.id;
      //         parentData.data = data;
      //         // 关闭最近弹窗
      //       }
      //     });
      //   });
      // } else {
      // }
    }

    // 是否是订单
    function isOrderFun(isTrue) {
      if (isTrue) {
        $("#orderIdBox").show();
        $('#addSkuPianFun').hide()
        // $("#orderTypeBox").show();
        // $("#orderCreatorNameBox").show();
        $("#residueQuantityBox").show();
        $("#orderRemarkBox").show();
        $("#demandQuantity").attr("disabled", true);
        $("#demandQuantityBox").show();
      } else {
        $("#orderIdBox").hide();
        $("#residueQuantityBox").hide();
        $("#orderRemarkBox").hide();
        $("#demandQuantity").attr("disabled", false);
        $("#demandQuantityBox").hide();
      }
    }
    $("#customerSkuCode").click(function () {
      //计划来源
      let planSource = $("#planSource").val();
      let orderId;
      if (planSource === "order") {
        orderId = $("#orderId").val();
        if (orderId === "" || orderId === undefined) {
          layer.msg("请选择订单编号", { icon: 2 });
          return false;
        }
      }
      admin.formOpen({
        area: ["80%", "85%"],
        title: "物料列表",
        style: "font-size: 20px;",
        path: "components/productionPlan/product_detail.html",
        success: function () {
          parentData.orderId = orderId;
          parentData.planId = data.id ? data.id : null;
        },
        end: function () {
          console.log(111);
          console.log(form.val("addProductionPlanFormDiv"));
        },
      });
      return false;
    });
    $("#addSkuPianFun").click(function () {
      let planSource = $("#planSource").val();
      if (!planSource) {
        layer.msg("请选择计划来源", { icon: 2 });
        return false;
      }
      let orderId = "";
      if (planSource === "order" || planSource === "finish") {
        orderId = $("#orderId").val();
        if (orderId === "" || orderId === undefined) {
          layer.msg("请选择订单编号", { icon: 2 });
          return false;
        }
      }
      admin.formOpen({
        area: ["80%", "85%"],
        title: "物料列表",
        style: "font-size: 20px;",
        path: "components/purchase/skuTableForm.html",
        success: function () {
          parentData.orderId = orderId;
          parentData.notInListIds = table.cache["skuPlanTable"]
            .map((v) => v.productDetailId)
            .join();
          // parentData.type = $("#planSource").val();
        },
        end: function () {
          if (childData.list && childData.list.length > 0) {
            let list = table.cache["skuPlanTable"];
            let chidList = childData.list.map((v) => {
              v.customerSkuCode = v.skuCode;
              v.customerSkuName = v.skuName;
              v.customerSkuSpec = v.skuSpec;
              v.planNature = "entirety";
              v.outputTime = "";
              v.shipmentTime = "";
              v.bookId = "";
              v.bookCode = "";
              v.remark = "";
            });
            list.push(...childData.list);

            table.reload("skuPlanTable", { data: list });
          }

          // let productDetailId = $("#productDetailId").val();
          // if (orderId) {
          //   let planSource = $("#planSource").val();
          //   // const { data } = await admin.reqPro("enterprise/sell/admin/order/detail/" + orderId, {});
          //   if (productDetailId) {
          //     const { data } = await admin.reqPro(
          //       `production/productionPlan/admin/productionPlan/getQuantityBy/${orderId}/${planSource}/${productDetailId}`
          //     );
          //     // let obj = data.orderProList.find((v) => v.productDetailId == productDetailId);
          //     form.val("addProductionPlanFormDiv", {
          //       demandQuantity: data.quality,
          //       residueQuantity: data.noQuantityNum,
          //       productionQuantity:
          //         data.noQuantityNum > 0 ? data.noQuantityNum : 0,
          //     });
          //     // $("#orderProId").val(orderProId);
          //   }
          // } else {
          // }
          // if (productDetailId) {
          //   console.log("productDetailId", productDetailId);
          //   initBenchmarkBookData(productDetailId);
          // }
        },
      });
      return false;
    });
    $("#checkSkuFun").click(function () {
      //计划来源
      let planSource = $("#planSource").val();
      let orderId = "";
      if (planSource === "order" || planSource === "finish") {
        orderId = $("#orderId").val();
        if (orderId === "" || orderId === undefined) {
          layer.msg("请选择订单编号", { icon: 2 });
          return false;
        }
      }
      admin.formOpen({
        area: ["80%", "85%"],
        title: "物料列表",
        style: "font-size: 20px;",
        path: "components/productionPlan/product_detail.html",
        success: function () {
          parentData.orderId = orderId;
          parentData.type = $("#planSource").val();
        },
        end: async function () {
          let productDetailId = $("#productDetailId").val();
          if (orderId) {
            let planSource = $("#planSource").val();
            // const { data } = await admin.reqPro("enterprise/sell/admin/order/detail/" + orderId, {});
            if (productDetailId) {
              const { data } = await admin.reqPro(
                `production/productionPlan/admin/productionPlan/getQuantityBy/${orderId}/${planSource}/${productDetailId}`
              );
              // let obj = data.orderProList.find((v) => v.productDetailId == productDetailId);
              form.val("addProductionPlanFormDiv", {
                demandQuantity: data.quality,
                residueQuantity: data.noQuantityNum,
                productionQuantity:
                  data.noQuantityNum > 0 ? data.noQuantityNum : 0,
              });
              // $("#orderProId").val(orderProId);
            }
          } else {
          }
          if (productDetailId) {
            console.log("productDetailId", productDetailId);
            initBenchmarkBookData(productDetailId);
          }
        },
      });
      return false;
    });

    $("#orderFun").click(function () {
      let type = $("#planSource").val();
      let title = "";
      let path = "";
      let detailUrl = "";
      if (type == "order") {
        title = "量产订单列表";
        path = "components/sell/massOrder.html";
        detailUrl = "enterprise/sell/admin/order/detail/";
      } else if (type == "finish") {
        title = "完成订单列表";
        path = "components/sell/finishedOrder.html";
        detailUrl = "enterprise/sell/admin/finishedOrder/detail/";
      }
      if (type && path && title) {
        admin.formOpen({
          area: ["80%", "85%"],
          title: title,
          path: path,
          success: function () {
            parentData.eventName = "radio";
          },
          end: async function () {
            form.val("addProductionPlanFormDiv", { ...orderObj });
            if (childData.list && childData.list.length > 0) {
              const res = await admin.reqPro(detailUrl + childData.list[0].id);
              let obj = res.data;
              let list = [];
              if (type == "order") {
                await initSkuPlanTable(
                  obj.orderProList,obj
                );
                form.val("addProductionPlanFormDiv", {
                  orderId: obj.id,
                  orderCode: obj.code,
                });
              } else if (type == "finish") {
                await initSkuPlanTable(obj.details,obj);
                form.val("addProductionPlanFormDiv", {
                  orderId: obj.id,
                  orderCode: obj.selCode,
                  // shipmentTime: obj.deliveryTime,
                });
              }
            }
          },
        });
      }
    });
    async function initSkuPlanTable(list,obj) {
      let skuIdList = list.map((v) => v.productDetailId);
      const { data } = await admin.reqPro(
        "enterprise/product/admin/productDetailWMS/list",
        {
          inIds: skuIdList.join(","),
        }
      );
      console.log(123,list);
      
      var listData = data.map((v) => {
        v.customerSkuCode = v.skuCode;
        v.customerSkuName = v.skuName;
        v.customerSkuSpec = v.skuSpec;
        v.planNature = "entirety";
        v.outputTime = "";
        v.shipmentTime = "";
        v.bookId = "";
        v.bookCode = "";
        v.remark = "";
        v.productDetailId = v.id;
        if(obj){
          if($("#planSource").val() === "order"){
            v.shipmentTime = obj.deliveryTime;
          }else if($("#planSource").val() === "finish"){
               v.shipmentTime = obj.planOnTime;
          }
        }
        if($("#planSource").val() === "order"){
          console.log(22222222);
          
          if(list.find((v1)=>v1.productDetailId === v.id)){
            
            v.productionQuantity = list.find((v1)=>v1.productDetailId === v.id).quantity;
          }
        }else if($("#planSource").val() === "finish"){
          if(list.find((v1)=>v1.productDetailId === v.id)){
            v.productionQuantity = list.find((v1)=>v1.productDetailId === v.id).selQuality;
          }
        }
        return v;
      });
      console.log(12,listData);
      console.log(12,data);
      window.setTimeout(()=>{
        table.reload("skuPlanTable", { data: listData });
      },100)
    }
    form.on("submit(addProductionPlanExamine)", function (d) {
      let status = $(d.elem).data("type");
      submitFun(d, status);
      return false;
    });
    form.on("submit(addProductionPlanFormSubmit)", function (d) {
      let status = $(d.elem).data("type");
      submitFun(d, status);
      return false;
    });
    $("#openImgTable").click(async function () {
      if (!$("#bookId").val()) {
        layer.msg("请先选择基准书", { icon: 2 });
        return false;
      }
      const res = await admin.reqPro(
        "enterprise/benchmarkBook/admin/benchmarkBook/detail/" +
        $("#bookId").val()
      );
      console.log(123, res.data.drawInfos);

      admin.formOpen({
        area: ["55%", "45%"],
        title: "附件列表",
        content: `<div id="imgTable" style='height:100%;overflow: auto;'>
            <table id="imgTableList" lay-filter="imgTableList">
            </table>
            </div>`,
        success: function () {
          table.render({
            elem: "#imgTableList",
            data: res.data.drawInfos,
            page: false,
            limit: 99999,
            cols: [
              [
                { type: "numbers", title: "序号" },
                { field: "drawName", title: "图片名称" },
                { field: "drawUrl", title: "图片地址" },
                {
                  title: "操作",
                  align: "center",
                  width: 160,
                  templet: function (d) {
                    return `<a class="layui-btn layui-btn-xs" type="button" lay-event="preview">预览</a>`;
                  },
                },
              ],
            ],
          });
          table.on("tool(imgTableList)", function (obj) {
            if (obj.event === "preview") {
              admin.formOpen({
                title: "图片预览",
                area: ["80%", "80%"],
                content: `<div style='overflow: hidden;height:100%;display:flex;justify-content: center;
  '><img style="height:100%" src="${obj.data.drawUrl}"/></div>`,
              });
            }
          });
        },
      });
    });
    $("#bookIdBox").click(function () {
      let customerSkuCode = $("#customerSkuCode").val();
      if (!customerSkuCode) {
        layer.msg("请先选择物料", { icon: 2 });
        return false;
      }
      // data.productDetailId = data.id;
      // admin.putTempData("benData", data ? data : null);
      // 展示ben的页面 显示物料类型
      let obj = form.val("addProductionPlanFormDiv");
      // data.productDetailId = data.id;
      admin.putTempData("benData", obj ? obj : null);
      admin.formOpen({
        area: "1400px",
        offset: "35px",
        title: "基准书管理",
        path: "components/product/benManager.html",
        success: function () {
          parentData.typeName = "redio";
        },
        end: async function () {
          console.log(childData.obj);
          let obj = childData.obj ? childData.obj : {};
          if (obj.statusName == "待初审") {
            layer.msg("基准书状态为待初审，无法生成生产计划！", { icon: 2 });
            return false;
          }
          form.val("addProductionPlanFormDiv", {
            bookId: obj.id,
          });
          if (obj.id) {
            if (obj.drawUrl) {
              form.val("addProductionPlanFormDiv", {
                accessoryFileId: obj.drawUrl,
              });
              $("#accessoryPath").html(
                "<a href='" +
                obj.drawUrl +
                "' target='_blank'>" +
                obj.drawUrl +
                "</a>"
              );
              // $("#accessoryBtn").hide();
              $("#accessoryFileId").val(obj.drawUrl);
            }
          }
        },
      });
    });
    $("#addBookFun").click(function () {
      let productDetailId = $("#productDetailId").val();
      if (!productDetailId) {
        layer.msg("请先选择物料", { icon: 2 });
        return false;
      }
      admin.req(
        "enterprise/product/admin/productDetailWMS/get",
        { productDetailId },
        (res) => {
          if (res.code == 200) {
            admin.formOpen({
              area: ["80%", "85%"],
              title: "添加基准书",
              path: "components/res/benchmarkBook/skuPlanTable.html",
              success: function () {
                parentData.eventName = "add";
                let obj = { ...res.data, productDetailId };
                delete obj.id;
                // obj.productType = obj.productTypeId;
                parentData.data = obj;
                parentData.type = "生产计划列表";
              },
              end: function () {
                initBenchmarkBookData(productDetailId);
              },
            });
          }
        }
      );

      return false;
    });
    function submitFun(d, status) {
      const formData = { ...d.field, status };
      formData.orderType = formData.planSource;
      formData.batchProductionPlansList = table.cache["skuPlanTable"];
      // if (formData.planNature == "process") {
      //   if (!formData.processId) {
      //     layer.msg("请选择工序", { icon: 2 });
      //     return false;
      //   }
      // }

      let isBookObj = formData.batchProductionPlansList.find((v) => {
        return !v.bookId;
      });
      if (isBookObj) {
        layer.msg("请选择料号名称为" + isBookObj.customerSkuCode + "的基准书", {
          icon: 2,
        });
        return false;
      }
      let isShipmentTimeObj = formData.batchProductionPlansList.find((v) => {
        return !v.shipmentTime;
      });
      if (isShipmentTimeObj) {
        layer.msg(
          "请输入料号名称为" +
          isShipmentTimeObj.customerSkuCode +
          "的生产截至时间",
          {
            icon: 2,
          }
        );
      }
      let isOutputTimeObj = formData.batchProductionPlansList.some((v) => {
        return !v.OutputTime;
      });
      if (isOutputTimeObj) {
        layer.msg(
          "请输入料号名称为" + isOutputTimeObj.customerSkuCode + "的交货时间",
          {
            icon: 2,
          }
        );
      }
      layer.load(2);
      console.log(123, formData);

      // return false;
      // if (nowData.eventName === "add") {
      admin.req(
        nowData.eventName === "add"
          ? "production/productionPlan/admin/productionPlan/addBatchPlan"
          : // ? "production/productionPlan/admin/productionPlan/add"
          "production/productionPlan/admin/productionPlan/update",
        JSON.stringify(formData),
        function (res) {
          layer.closeAll("loading");
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("productionPlanTable");
            layer.closeAll("page");
            if (
              nowData.planSourceType == "order" ||
              nowData.planSourceType == "finish"
            ) {
              // 弹窗 是否跳转生产计划页面
              let layInex = layer.confirm(
                "添加成功，是否跳转生产计划页面？",
                { icon: 3, title: "提示" },
                function (index) {
                  location.href = "index.html#/productionPlan/productionPlan";
                  layer.close(layInex);
                }
              );
            }
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        nowData.eventName === "add" ? "POST" : "PUT",
        false,
        "application/json"
      );
      // }
      return false;
    }
  });
</script>
<style>
  #skuPlanTable .layui-input-block {
    margin-left: 130px;
  }

  #skuPlanTable .layui-form-label {
    width: 100px;
  }

  #skuPlanTableModel .layui-table-cell {
    overflow: visible !important;
  }
</style>